package com.autohammal.save.util;

import java.io.File;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.autohammal.ITarget;
import com.autohammal.monitor.AbstractMonitor;
import com.autohammal.monitor.SchedulerMonitor;
import com.autohammal.save.Saveable;
import com.autohammal.save.util.NameGengerator.Style;

public class XMLUtil {
	public static final String ROOT_NODE = "save";
	public static final String ENTRY_NODE = "save-entry";
	public static final String MONITOR_NODE = "save-monitor";
	public static final String TARGET_NODE = "save-target";

	public static final String TYPE_ATTRIBUTE = "type";
	public static final String LINK_ATTRIBUTE = "link";
	public static final String STAMP_ATTRIBUTE = "stamp";

	public static void buildSaveEntryXML(Map<Saveable, File> map) {
		if (map == null)
			return;
		Document document = DocumentHelper.createDocument();
		Element rootElement = document.addElement(ROOT_NODE);
		rootElement.addComment("An XML save point");
		for (Map.Entry<Saveable, File> entry : map.entrySet()) {
			Saveable sa = entry.getKey();
			File sapath = entry.getValue();
			if (sa instanceof SchedulerMonitor) {
				AbstractMonitor monitor = (AbstractMonitor) sa;
				Element entryElement = rootElement.addElement(ENTRY_NODE);
				Element monitorElement = entryElement.addElement(MONITOR_NODE);
				monitorElement.addAttribute(TYPE_ATTRIBUTE, sa.getClass()
						.getName());
				monitorElement.addAttribute(LINK_ATTRIBUTE,
						sapath.getAbsolutePath());
				monitorElement.addAttribute(STAMP_ATTRIBUTE,
						NameGengerator.generate(Style.TIME));
				ITarget target=monitor.getTarget();
				if(target!=null && target instanceof Saveable){
				Element targetElement = monitorElement.addElement(TARGET_NODE);
				targetElement.addAttribute(TYPE_ATTRIBUTE, target.getClass()
						.getName());
				targetElement.addAttribute(TYPE_ATTRIBUTE, target.getClass()
						.getName());
				}
			}

		}

	}
}
